<?php

namespace backend\models;

use Yii;
use liangzoe\mobilesmser\TextSmser;
use PHPThumb\GD;

/**
 * This is the model class for table "sys_image".
 *
 * @property integer $id
 * @property integer $type
 * @property string $name
 * @property string $url
 * @property string $url_menu
 * @property integer $width
 * @property integer $height
 */
class Image extends \yii\db\ActiveRecord
{
    public $imageFile;
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'sys_image';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['type', 'width', 'height'], 'integer'],
         //   [['type'], 'required'],
            [['name'], 'string', 'max' => 64],
            [['url'], 'string', 'max' => 128]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'type' => 'Type',
            'name' => 'Name',
            'url' => 'Url',
            'width' => 'Width',
            'height' => 'Height',
        ];
    }
    public function get_img_id($url)
    {
    	$_arr = explode('.', $url);
    	$_string_tmp = str_replace('_1', '', $_arr[0]);
    	//var_dump($_arr);
    	 
    	$_string = str_replace('_2', '', $_string_tmp); //大图
    	$arr_big_img = array($_string,$_arr[1]);
    	$big_img = implode('.', $arr_big_img);
    	$big_img_id = (Image::findOne(['url'=>$big_img]) != null)?Image::findOne(['url'=>$big_img])->id:'';
    	 
    	 
    	$_string_1 = $_string.'_1'; //中图
    	$arr_thumb_img = array($_string_1,$_arr[1]);
    	$thumb_img = implode('.', $arr_thumb_img);
    	$thumb_img_id = (Image::findOne(['url'=>$thumb_img]) != null)?Image::findOne(['url'=>$thumb_img])->id:'' ;
    	 
    	$_string_2 = $_string.'_2';//小图
    	$arr_small_img = array($_string_2,$_arr[1]);
    	$small_img = implode('.', $arr_small_img);
    	$small_img_id = (Image::findOne(['url'=>$small_img]) != null)?Image::findOne(['url'=>$small_img])->id:'';
    	 
    	return array('big_img_id'=>$big_img_id,'thumb_img_id'=>$thumb_img_id,'small_img_id'=>$small_img_id);
    	 
    }
    public static function show_image($id)
    {
    	if(Image::findOne($id) != null)
    	{
    		return Image::findOne($id)->url;
    	}
    }
    
    public static function findImageByImageIDOrImagename($earch)
    {
    	 if($this->findImageByImageID($earch) != null)
    	 {
    	 	return $this->findImageByImageID($earch);
    	 }
    	 if($this->findImageImagename($earch) != null)
    	 {
    	 	return $this->findImageImagename($earch);
    	 }
    	 return null;
    }
    public function findImageByImageID($earch)
    {
    	return Image::findAll(['id'=>$earch]);
    }
    public function findImageImagename($earch)
    {
    	return Image::findAll(['name'=>$earch]);
    }
  /**


     * @return multitype:string boolean Ambigous <boolean, number>
     */
    /**
     * 共用--存入数据到文件夹，并获取缩略图，三种图片的id
     * 压缩比例通过配置表设置
     * 新增或更新 根据图片id
     * @param unknown $model(图片模型)
     * @param unknown $file_menu(图片分类)
     * @param unknown $image_name(图片名称)
     * @param unknown $thumb_type(中图压缩名称)
     * @param unknown $small_type(小图压缩名称)
     * @return multitype:string Ambigous <unknown, boolean> Ambigous <boolean, number>
     */
    public static function save_image_to_files($model,$file_menu,$image_name,$thumb_type,$small_type,$img_url_id=0,$img_thumb_id=0,$img_small_id=0)
    {
    	
    	$uuid = md5(uniqid());
    	$uuid_a =  substr($uuid, 0,3);
    	$uuid_b =substr($uuid, 3,3);
    	$uuid_c = substr($uuid, 6,3);
    	$uuid_d =  substr($uuid, 9,3); 	 
    	$uuid_file_name =  substr($uuid, 12,20); 	 
    	$folder = Yii::getAlias('@webroot').'/images/'.$uuid_a.'/'.$uuid_b.'/'.$uuid_c.'/'.$uuid_d;
    	TextSmser::make_dir($folder);
    	   	
    	$file_save_addr = 'images/'.$uuid_a.'/'.$uuid_b.'/'.$uuid_c.'/'.$uuid_d.'/'.$uuid_file_name; //实际位置   	 
    	$model->image_upload->saveAs(Yii::getAlias('@webroot').'/'.$file_save_addr.'.'.$model->image_upload->extension);
    	
    	$image_addr = $file_save_addr.'.'.$model->image_upload->extension;
    	$image_url = $file_menu;
    	$image_w = getimagesize(Yii::getAlias('@webroot').'/'.$file_save_addr.'.'.$model->image_upload->extension)[0];
    	$image_h = getimagesize(Yii::getAlias('@webroot').'/'.$file_save_addr.'.'.$model->image_upload->extension)[1];
    	if (empty($img_url_id)){
        	$img_url_id = self::newimage($image_name,$image_addr, $file_menu, $image_w, $image_h);
    	} 
    	else {
    	    self::updateimage($img_url_id, $image_name, $image_addr, $image_w, $image_h);
    	} 
    	
    	$img_show = '<img style="margin:20px 10px 0px 0px;width:30%;" src="'.Yii::getAlias('@web').'/'.$file_save_addr.'.'.$model->image_upload->extension.'">';
    	$img_url = $file_save_addr.'.'.$model->image_upload->extension; 
    	
    	$thumb_ratio = PrfConfig::get_config_value($thumb_type); //压缩的比例
    	$small_ratio = PrfConfig::get_config_value($small_type); //压缩的比例
    	//生成缩略图并记录到数据库（中图）,大于990的时候
    	//if( $image_w / 2 >= 990)
    	if( $thumb_ratio >0 )
    	{	    
    		$thumb = new GD(Yii::getAlias('@webroot').'/'.$file_save_addr.'.'.$model->image_upload->extension); //原图
	    	//$thumb->resize($width1,$height1);
	    	$thumb->resizePercent($thumb_ratio);
	    	$file_save_addr_thumb = $file_save_addr.'_1';//实际位置
	    	$thumb->save(Yii::getAlias('@webroot').'/'.$file_save_addr_thumb.'.'.$model->image_upload->extension);
	    
	    	$image_addr_thumb = $file_save_addr_thumb.'.'.$model->image_upload->extension;
	    	$image_url_thumb = $file_menu;//虚拟目录（图片类别）
	    	$image_w_thumb = getimagesize(Yii::getAlias('@webroot').'/'.$file_save_addr_thumb.'.'.$model->image_upload->extension)[0];
	    	$image_h_thumb = getimagesize(Yii::getAlias('@webroot').'/'.$file_save_addr_thumb.'.'.$model->image_upload->extension)[1];
	    	
	    	if(empty($img_thumb_id))
	    	$img_thumb_id = self::newimage($image_name.'_thumb',$image_addr_thumb, $file_menu, $image_w_thumb, $image_h_thumb);
	    	else self::updateimage($img_thumb_id, $image_name.'_thumb', $image_addr_thumb, $image_w_thumb, $image_h_thumb);
	    	
	    	$img_show .= '<img style="margin:20px 10px 0px 0px;" src="'.Yii::getAlias('@web').'/'.$file_save_addr_thumb.'.'.$model->image_upload->extension.'">';
	    	$img_thumb_url = $file_save_addr_thumb.'.'.$model->image_upload->extension;
    	}
    	else 
    	{
    		$img_thumb_id = $img_url_id;
    	}

    	
    	//生成缩略图并记录到数据库（小图）
    	//if( $image_w /4 >=  300)
    	if( $small_ratio >0 )
    	{
	    	//$thumb->resize($width2,$height2);
	    	$small = new GD(Yii::getAlias('@webroot').'/'.$file_save_addr.'.'.$model->image_upload->extension);//原图
	    	$small->resizePercent($small_ratio);
	    	$file_save_addr_small = $file_save_addr.'_2';//实际位置
	    	$small->save(Yii::getAlias('@webroot').'/'.$file_save_addr_small.'.'.$model->image_upload->extension);
	        
	    	$image_addr_small = $file_save_addr_small.'.'.$model->image_upload->extension;
	    	$image_url_small = $file_menu;//虚拟目录（图片类别）
	    	$image_w_small = getimagesize(Yii::getAlias('@webroot').'/'.$file_save_addr_small.'.'.$model->image_upload->extension)[0];
	    	$image_h_small = getimagesize(Yii::getAlias('@webroot').'/'.$file_save_addr_small.'.'.$model->image_upload->extension)[1];
	    
	    	if(empty($img_small_id)){
	    	    $img_small_id = self::newimage($image_name.'_small',$image_addr_small, $file_menu, $image_w_small, $image_h_small);
	    	}else{
	    	    self::updateimage($img_small_id, $image_name.'_small', $image_addr_small, $image_w_small, $image_h_small);
	    	}
	    	
	    	$img_show .= '<img style="margin:20px 10px 0px 0px;" src="'.Yii::getAlias('@web').'/'.$file_save_addr_small.'.'.$model->image_upload->extension.'">';
	    	$img_show = '<div style="text-align:center;'.'">'.$img_show.'</div><div style="text-align:center;color:green;font-weight:bold;font-size:15px;">上传成功！</div>';
	    	$img_small_url = $file_save_addr_small.'.'.$model->image_upload->extension;
	    	
    	}
    	else
    	{
    		$img_small_id= $img_url_id;
    	}
    	
    	return array('img_url_id'=>$img_url_id,'img_thumb_id'=>$img_thumb_id,'img_small_id'=>$img_small_id,'img_show'=>$img_show);
    	 
    }
    /**
     * 共用-在数据表sys_image写入新图片
     * @param unknown $image_addr
     * @param unknown $image_url
     * @param unknown $image_w
     * @param unknown $image_h
     * @return boolean
     */
	     public static function newimage($image_name,$image_addr,$file_menu,$image_w,$image_h)
    {
    	$model_image = new Image();
    	$model_image->name = $image_name;
    	$model_image->url = $image_addr;
    	$model_image->type = $file_menu;
    	$model_image->width = $image_w;
    	$model_image->height = $image_h;
    	$model_image->update_time = time();
    	if($model_image->save())
    	{
    		return $model_image->id;
    	}
    }
    
    /**
     * 更新图片
     */
    public static function updateimage($image_id,$name,$url,$image_w,$image_h){
    	$model = self::findOne(['id'=>$image_id]);
    	$model->name = $name;
    	$model->url = $url;
    	$model->width = $image_w;
    	$model->height = $image_h;
    	$model->update_time = time();
    	if($model->save()) return true;
    }
    /**
     * 上传财务类凭证
     * @param unknown $model
     * @return string
     */
    public static function save_file($model){
    	$uuid = md5(uniqid());
    	$date = date('Y-m-d',time());
    	$folder = Yii::getAlias('@webroot').'/finance/'.$date;
    	TextSmser::make_dir($folder);
    	$file_addr = $folder.'/'.$uuid.'.'.$model->file->extension;
    	$model->file->saveAs($file_addr);
    	return 'finance/'.$date.'/'.$uuid.'.'.$model->file->extension;
    
    }
    public static function resizeImage($root,$sourcePath, $width, $height, $targetPath,$quality=80,$copy=true)
    {
        //$root:        /home/www/gjj/backend/web/
        //$sourcePath:  images/x/y/z.jpg
        //$targetPath:  images/a/b/c.jpg
        $fileFullPath = $root.$sourcePath;
        $ext = explode(".", $fileFullPath);
        $ext = $ext[count($ext)-1];
    
        if($ext == "jpg" || $ext == "jpeg")
            $im = imagecreatefromjpeg($fileFullPath);
        elseif($ext == "png")
            $im = imagecreatefrompng($fileFullPath);
        elseif($ext == "gif")
            $im = imagecreatefromgif($fileFullPath);
    
            $x = round(imagesx($im));
            $y = round(imagesy($im));
    
            if($x <= $width && $y <= $height)
            {
                if ($copy){
                    copy($root.$sourcePath, $root.$targetPath);
                }else{
                    rename($root.$sourcePath, $root.$targetPath);
                }
                return ['width'=>$x,'height'=>$y,'path'=>$targetPath];
            }
            if($x >= $y) {
                $newx = round($width);
                $newy = round($newx * $y / $x);
            }
            else {
                $newy = round($height);
                $newx = round($x / $y * $newy);
            }
    
            $im2 = imagecreatetruecolor($newx, $newy);
            if($ext == "png" || $ext == "gif"){
                $color  = imagecolorallocate($im2,255,255,255);
                imagecolortransparent($im2,$color);
                imagefill($im2,0,0,$color);
            }
            imagecopyresampled($im2, $im, 0, 0, 0, 0, floor($newx), floor($newy), $x, $y);
            if($ext == "jpg" || $ext == "jpeg")
                imagejpeg($im2,$root.$targetPath,$quality);
            elseif($ext == "png")
                imagepng($im2,$root.$targetPath);
            elseif($ext == "gif")
                imagegif($im2,$root.$targetPath);
            else
                return false;
        return ['width'=>$newx,'height'=>$newy,'path'=>$targetPath];
    }
    /*
     * 更新图片而不改变ID
     * 传入限制的最大宽度和最大高度
     */
    public function changeImageFile($width,$height)
    {
        if ($this->imageFile){
            $ext = $this->imageFile->extension;
            $root = Yii::getAlias('@webroot/');
            $sourcePath = 'tmp/'.(strtotime('now').mt_rand(1000000,9999999)).'.'.$ext;
            if ($this->imageFile->saveAs($root.$sourcePath)){
                
                $targetPath = $this->url;
                $newFile = self::resizeImage($root, $sourcePath, $width, $height, $targetPath);
                $this->width = $newFile['width'];
                $this->height = $newFile['height'];
                $this->url = $targetPath;
                return true;
            }else{
                return false;
            }
        }else{
            return false;
        }
    }
}
